<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/26
 * Time: 10:53
 * Desc: index - old
 */
namespace app\index\controller;
use controller\BasicWechat;
use app\comm\service\SendMsgService;
use app\comm\service\UserService;
use app\comm\service\WeixinService;
use app\comm\service\GoodsService;
use app\comm\service\SrotGoodServices;
use app\comm\service\UserOrderService;
use \think\Loader;
use \think\Db;
use \think\Controller;
use app\comm\controller\WebLogController;
use ServS\Map\BaidDuMap;
use app\index\service\FansService;
use think\Cookie;
use app\comm\service\CityService;
/**
 * 网站入口控制器
 */
const LABEL_FONT_PATH_DEFAULT = '';
class Index_old extends WebLogController{

    protected $srogood;
    public function __autoindex(){
        $this->srogood = new SrotGoodServices;
    }

    /**
     * 网站入口
     */
    public function index($la=120.4385574309,$ln=36.076404325348) {
        $cityservice = new CityService();
        $citylist = $cityservice->getCityListByCache();
        $this->assign('citylist',$citylist);
        $this->assign('citylistjson',json_encode($citylist));
        $city = request()->get("city");
        if(!empty($city)){
            $int  =  900000;
            Cookie::set("city",$city,time()+$int);
        }
        if(Cookie::has("city")){
            $city = Cookie::get("city");
        }
        $list =  $this->srogood->storlist($la,$ln,$city);
        $this->assign('list',$list);

        return view('index/index');
    }

    /**
     * 定位
     */
    public function dinwei(){
        return view('index/dinwei');
    }

    /**
     * 定位获取地理信息
     */
    public function wezhi(){
        $baidumap = new BaidDuMap;
        $rwel =$baidumap ->getbylatlnt(35.948726,120.153084);
        return json($rwel);
    }

    /**
     * 进入门店
     */
    public function store(){
        $id = request()->get("id");
        session('store_id',$id);
        //@lingyun   2018-01-03
        $fansservice = new FansService();
        $fansservice->getStoreAttentionCoupon(session('_user_uid_.uid'),$id);
        //获取微信分享参数
        $signPackage = $fansservice->wxShare();
        //分享的内容
        $share = array(
            'title'=>'测试分享',
            'link'=>request()->url(true)."&sharer=73",
//            'link'=>request()->url(true)."&sharer=".session("_user_uid_.uid"),
            'desc'=>'测试分享',
            'imgUrl'=>"http://oygwasu3y.bkt.clouddn.com/bf693339f478499c/ec092e932d374160.jpg"
        );
        $this->assign('share',$share);
        $this->assign('signPackage',$signPackage);
        //@lingyun   2018-01-03

        // $page =   $this->request ->get('page','1','');
        // $list =   $this->srogood->getstorgoods($id,$page=1);
        // return json($list);

        $list =[];
        return view('index/store',['list'=>$list,'storeid'=>$id]);
    }



    /**
     * 获取店铺商品，ajax
     */
    public function goodscatage(){
        $list =   $this->srogood->getcatagstorgoods();
        return json( $list);
    }

    /**
     * 搜索
     */
    public function serch(){
        $page=request()->get("page");
        $limit=request()->get("limit");
        $msg =request()->get("msg");
        $id  =request()->get("id");
        $catge=request()->get("catge");
        $store_id=request()->get("storeid");;
        $map["store_id"]=["eq",$store_id];
        if($catge!=""){
            $map["cat_id"]=["eq",$catge];
        }
        if($msg!=''){
            $map["name"]=["like","%".$msg."%"];
        }
        $resutl = Db::table("ys_view_storgood")->where($map)->page($page,$limit)->select();
        foreach ($resutl as $key => &$value) {
            $value["detail"]=htmlspecialchars_decode($value["detail"]);
        }
        return json($resutl);
    }

    /**
     * 商品详情,获取商品的id
     * @return [type] [description]
     */
    public function goods(){
        $goodspecname = new \app\index\service\GoodSpec();
        $id = request()->get("id");
        $storeid         =   $this->request->get('storeid');
        $map["goods_id"] = ["eq",$id];
        //属性
        $goodspace = Db::table("ys_goods_spec")->where($map)->group('spec_id')->select();
        foreach ($goodspace as $key => &$value) {
            $value["spec"]     =   $goodspecname ->goodspec($value["spec_id"],$id);
            $value["specname"] =   $goodspecname ->getys_goods_spec_name($value["spec_id"]);
        }

        $goods = Db::table("ys_goods")->where("id",$id)->find();

        //没有属性的商品 价格与kucun
        if($goods["is_spec"]=="0"){
            $goodspec = Db::table("ys_goods_spec_detail")->where("goods_id",$id)->find();
            $this->assign('goodspec',$goodspec);
            $goodstoresock = Db::table("ys_store_goods_stock")->where("goods_id",$id)->find();
            //dd($goodspec);
            $this->assign('goodstoresock',$goodstoresock);

        }
        $this->assign('stock',9999);
        $this->assign('goods',$goods);
        $this->assign('storeid',$storeid);
        $this->assign('goodspace',$goodspace);
        return view('index/goods');
    }

    /**
     * ajax   （商品库存）
     * 获取商品的库存，商品的数量
     */
    public  function getgoodsajax(){
        $specid = request()->get("param");
        $ary  = explode(",",$specid);
        //升续
        asort($ary);
        $str = implode(",",$ary);
        $stor_good_stock_map["specs"]=["eq",$str];
        $store_goods_stock = Db::table("ys_store_goods_stock")->where($stor_good_stock_map)->find();
        $spec_good_detai_map["specs"]=["eq",$str];
        $goods_spec_detail = Db::table("ys_goods_spec_detail")->where($spec_good_detai_map)->find();
        $data["storegoodsstock"]= $store_goods_stock;
        $data["goodsspecdetail"]= $goods_spec_detail;
        return json(["status"=>1,"data"=>$data]);
    }

    //商品属性api
    public function goodsapi(){
        $goodspecname = new \app\index\service\GoodSpec();
        $id = request()->get("id");
        //属性有两种
        $map["goods_id"] = ["eq",$id];
        $goodspec = Db::table("ys_goods_spec")->where($map)->group('spec_id')->select();
        foreach ($goodspec as $key => &$value) {
            $value["spec"]     =   $goodspecname ->goodspec($value["spec_id"],$id);
            $value["specname"] =   $goodspecname ->getys_goods_spec_name($value["spec_id"]);
        }
        //商品
        $goods = Db::table("ys_goods")->where("id",$id)->find();
        return json(["goodspeci"=>$goodspec,"goods"=>$goods]);
        //return json(["status"=>1,"data"=>$goods]);
    }

    //利用商品属性 获取商品的库存等
    public function goodsstoreapibyspec(){
        $msg = request()->get("msg");
        $map["specs"] = ["eq",$msg];
        $goodspec = Db::table("ys_goods_spec_detail")->where($map)->find();
        //$goodskucun = Db::table("ys_store_goods_stock")->where("id")->find();
        return  $goodspec;
    }

    /**
     * 获取附近的门店
     */
    public function getstor(){
        $la = request()->get("la");
        $ln = request()->get("ln");
        $list =   $this->srogood->storlist($la,$ln);
        return  json($list);
    }

    /**
     * 订单回复您机制
     */
    public function orderrollback(){
        $userorderservice = new UserOrderService;
        $ord = $userorderservice->orderrollback();
    }

    //订单测试
    public function test(){
    }


    /**************************@Author  lingyun   ******************************************************/
    /**
     * @Author  lingyun
     * @Desc    进入商城首页
     */
    public function mall_index(){
        $where_city = [
            'status'=>1,
            'is_deleted'=>0
        ];
        //可用城市列表
        $city = db('city')->where($where_city)->select();
        $this->assign('city',$city);
        return $this->fetch('mall_index');
    }

    /**
     * @Author  lingyun
     * @Desc    获取城市门店列表
     */
    public function get_store_list(){
        $post = input('param.');
        //将城市的编号存入session中
        if(!empty($post['city_key'])){
            session('city_key',$post['city_key']);
        }
        $where_store = [
            'is_deleted'=>0,
            'status'=>1,
            'city_key'=>session('city_key')
        ];
        if(!empty($post['title'])){
            $this->assign('title',$post['title']);
            $where_store['title'] = ['like','%'.$post['title'].'%'];
        }else{
            $this->assign('title','');
        }
        if(empty($post['lng']) || empty($post['lat'])){
//            halt($where_store);
            $store_arr = db('store')->where($where_store)->order('dis_order desc')->select();
        }else{
            //门店排序
            $store_arr = db('store')->where($where_store)->order('2*asin(sqrt(pow(sin('.$post["lat"].'-lat/2),2)+cos('.$post["lat"].')*cos(lat)*pow(sin('.$post["lng"].'-lng/2),2)))*6378.137*1000 asc')->select();
        }
        $this->assign('store_list',$store_arr);
        $this->assign('city_key',session('city_key'));
        return $this->fetch('store_list');
    }

    /**
     * @Author  lingyun
     * @Desc    门店首页
     * @Desc    门店轮播图片、首次进入门店的会员领取门店关注券、门店推荐商品列表、门店推荐商品的分类
     * @Desc    订单详情表里面的goods_id关联ys_goods的主键  spec_id关联的是
     */
    public function store_index(){
        //门店id
        $store_id = input('id');
        if(!empty($store_id)){
            //门店id
            session('store_id',$store_id);
        }
        $where_category = [
            'is_deleted'=>0,
            'is_exp'=>0
        ];
        //顶部导航
        $category = db('goods_category')->where($where_category)->select();

        //门店顶部轮播图位
        $where_banner = [
            'status'=>1,
            'store_id'=>$store_id,
            'is_deleted'=>0,
            'bap_id'=>4     //门店首页顶部轮播图
        ];
        //门店的轮播图片
        $banner = db('store_banner')->where($where_banner)->order('dis_order desc')->select();
        //商品标签
        $goods_label = db('goods_label')->where(['status'=>1,'is_deleted'=>0])->select();
        //门店广告位一
        $where_advert_1 = [
            'adp_id'=>1,
            'store_id'=>$store_id       //门店id
        ];
        //门店广告位一
        $advert_1 = db('store_advert_list')->where($where_advert_1)->find();

        //门店广告位二
        $where_advert_2 = [
            'adp_id'=>2,
            'store_id'=>$store_id
        ];
        //门店广告位二
        $advert_2 = db('store_advert_list')->where($where_advert_2)->find();

        //门店优惠券
        $where_coupon = [
            'a.status'=>1,
            'a.is_recommend'=>1,
            'a.is_deleted'=>0
        ];

        $coupon = db('store_coupon')->alias('a')->join('ys_user_ycard b','a.id=b.coupon_id','LEFT')->where($where_coupon)->field('a.*,IFNULL(b.coupon_id,0) as is_receive')->limit(2)->select();
        //门店推荐商品分类
        //推荐商品分类一位
        $where_category_1 = [
            'a.store_id'=>$store_id,
            'a.is_deleted'=>0,
            'p_id'=>1
        ];
        //推荐商品二位
        $where_category_2 = [
            'a.store_id'=>$store_id,
            'a.is_deleted'=>0,
            'p_id'=>2
        ];
        //推荐商品分类id
        $recommend_category_1 = db('store_recommend_category')->alias('a')->where($where_category_1)->join('ys_goods_category b','a.cate_id=b.id','LEFT')->field('a.*,b.title')->order('a.p_id asc')->find();
        $recommend_category_2 = db('store_recommend_category')->alias('a')->where($where_category_2)->join('ys_goods_category b','a.cate_id=b.id','LEFT')->field('a.*,b.title')->order('a.p_id asc')->find();

        //推荐的商品
//        $cate_id = implode(',',array_values(array_unique(array_column($recommend_category, 'cate_id'))));
        $where_recommend_goods_1 = [
            'a.store_id'=>$store_id,
            'a.is_deleted'=>0,
            'a.status'=>1,
            'a.cate_id'=>$recommend_category_1['cate_id'],
        ];
        $where_recommend_goods_2 = [
            'a.store_id'=>$store_id,
            'a.is_deleted'=>0,
            'a.status'=>1,
            'a.cate_id'=>$recommend_category_2['cate_id'],
        ];
        //推荐商品一位
        $recommend_goods_1 = db('store_recommend_goods')->alias('a')->join('ys_store_goods_stock c','a.goods_id=c.id','LEFT')->join('ys_goods b','c.goods_id=b.id','LEFT')->where($where_recommend_goods_1)->field('a.*,b.name,b.price,c.goods_label')->select();
        foreach($recommend_goods_1 as $k1 => $v1){
            $recommend_goods_1[$k1]['goods_label'] = explode(',',$v1['goods_label']);
        }

        //推荐商品二位
        $recommend_goods_2 = db('store_recommend_goods')->alias('a')->join('ys_store_goods_stock c','a.goods_id=c.id','LEFT')->join('ys_goods b','c.goods_id=b.id','LEFT')->where($where_recommend_goods_2)->field('a.*,b.name,b.price,c.goods_label')->select();
        foreach($recommend_goods_2 as $k2 => $v2){
            $recommend_goods_2[$k2]['goods_label'] = explode(',',$v2['goods_label']);
        }


        $this->assign('category',$category);                     //顶部商品分类导航
        $this->assign('banner',$banner);                         //顶部轮播图
        $this->assign('advert_1',$advert_1);                     //广告位一
        $this->assign('advert_2',$advert_2);                     //广告位二
        $this->assign('coupon',$coupon);                         //门店推荐关注券
        $this->assign('recommend_category_1',$recommend_category_1); //推荐商品分类
        $this->assign('recommend_category_2',$recommend_category_2); //推荐商品分类
        $this->assign('recommend_goods_1',$recommend_goods_1);       //门店推荐商品
        $this->assign('recommend_goods_2',$recommend_goods_2);       //门店推荐商品
        $this->assign('goods_label',$goods_label);               //商品标签
        return $this->fetch('store_index');
    }

    /**
     * @Author  lignyun
     * @Desc    门店代金券
     */
    public function cash_coupon_list(){
        $store_id = session('store_id');
        $where_store_coupon = [
            'store_id'=>['eq',$store_id],
            'type'=>['eq',2],
            'status'=>['eq',1],
            'is_deleted'=>['eq',0]
        ];
        $list = db('store_coupon')->where($where_store_coupon)->select();
        $this->assign('list',$list);
        return $this->fetch('cash_coupon_list');
    }

    /**
     * @Author  lignyun
     * @Desc    购买
     */
    public function post_cash_coupon(){
        $id = input('id');      //代金券id
        $where = [
            'uid'=>['eq',session('_user_uid_.uid')],
            'id'=>['eq',$id]
        ];
        $coupon = db('store_coupon')->where('id',$id)->find();
        $result = db('cash_coupon_list')->where($where)->field('count(*) as count,uid,cash_coupon_id')->find();
        if(!empty($result)){
            if($result['count'] >= $coupon['create_num']){
                $this->error('每人限购数量已达上限，不能再次购买',url('Index/store')."?id=".session('store_id'));
            }
        }
        $this->assign('coupon',$coupon);
        return $this->fetch('post_cash_coupon');
    }

    /**
     * @Author  lignyun
     * @Desc    余额购买代金券
     */
    public function buy_cash_coupon(){
        $post = input('param.');
        $uid = session("_user_uid_.uid");
        $where_user['uid'] = ['eq',$uid];
        //会员信息
        $member = db('user')->where($where_user)->field('uid,user_money,realname,level_point,pay_points')->find();

        $where_coupon['id'] = ['eq',$post['id']];
        //代金券信息
        $coupon = db('store_coupon')->where($where_coupon)->find();

        if($coupon['price']>$member['user_money']){
            $this->error('您当前的余额已不足，请选择其他付款方式','');
        }
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cash_coupon_id'=>$post['id'],
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>$post['pay_type'],
            'pay_status'=>1,
            'price'=>$coupon['price'],
            'remark'=>'支付成功',
            'addtime'=>time()
        ];
        db('cash_coupon_list')->insert($data_arr);
        $data_arr1 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'order_sn'=>$data_arr['order_sn'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'pay_type'=>3,
            'amount'=>$coupon['price'],
            'cur_amount'=>$member['user_money'] - $coupon['price'],
            'sign'=>2,
            'charge_cn'=>'购买代金券',
            'addtime'=>time()
        ];
        db('user_wallet_log')->insert($data_arr1);
        $where_point_rule['id'] = ['eq',2];
        $point_rule = db('sys_point')->where($where_point_rule)->find();
        //变更的积分
        $point = ceil($coupon['price']/10);
        $data_arr2 = [
            'uid'=>$uid,
            'store_id'=>session('store_id'),
            'uidtype'=>1,
            'signid'=>2,
            'type'=>1,
            'point'=>$point,
            'curpoint'=>$member['pay_points']+$point,
            'type_cn'=>'购买代金券赠送积分',
            'remark'=>'购买代金券赠送积分',
            'addtime'=>time(),
        ];
        db('user_point_log')->data($data_arr2)->insert();
        $cur_level_point = $member['level_point']+$point;
        $cur_pay_point = $member['pay_points']+$point;
        $point_rule = db('sys_level')->select();
        $level = userLevel($point_rule,$cur_level_point);
        $data_arr3 = [
            'uid'=>$uid,
            'user_money'=>$member['user_money']-$coupon['price'],
            'level_point'=>$cur_level_point,
            'pay_points'=>$cur_pay_point,
        ];
        db('user')->data($data_arr3)->update();
        $this->success('支付成功','');
    }

}
